$(function(){  
    
    function format(){
        $("#num_preco").priceFormat();
    }
    
    function close(){
        $('#grid_dialog_service').dialog('destroy');
        $('#grid_dialog_service').remove();
        $('#grid_service').jqGrid('GridUnload');
        $('#pager_service').remove();
                  
    }
    
    function clean(){
        $("#id_servico").val("");
        $("#nom_servico").val("");
        $("#des_servico").val("");
        $("#num_preco").val("");
    }
         
    function cadastro_servico(){
        loading(true);
        $.post('service/sign', {
            'service.id' : $("#id_servico").val(),
            'service.name': $("#nom_servico").val(),
            'service.description' : $("#des_servico").val(),
            'service.price' : $("#num_preco").val().replace("R$ ", "").split(".").join("").replace(",", ".")  //replace(".", "").replace(",", ".")               
        }, function(data){
            loading(false);
            try {                                
                if(data.success === true) {
                    
                    if($("#id_servico").val() == '') {
                        alert(data.message);                    
                    } else {
                        alert("Alteração realizada com sucesso!");                    
                    }                  
                    $("#id_servico").val(data.service.id);
                } else {
                   alert(data.message);
                }
            } catch(e) {
                alert("Atenção!, ocorreu um erro em sua solicitação, tente novamente mais tarde.\n Detalhes: " + e.getMessage());
            }  
            
        });
    }
    
    function excluir_servico(id) {
        loading(true);
        $.post('service/delete', {
            'id' : id
        }, function(data){
            loading(false);
            try {                                
                if(data.success === true) {                                       
                    alert(data.message);     
                    $("#grid_service").trigger("reloadGrid");
                } else {
                    alert(data.message);
                }
            } catch(e) {
                alert("Atenção!, ocorreu um erro em sua solicitação, tente novamente mais tarde.\n Detalhes: " + e.getMessage());
            }              
        });
    }
    
  
    $("#button_cadastro_servico").click(function(){
        $("#div_temp").load("jform/forms.jsp #form_cadastro_servico", function(){
            $("#form_cadastro_servico").dialog({
                title : "Cadastro Serviço",
                width: 500,
                modal: true,
                resizable: false,
                open : function (){
                   
                    $('.ui-dialog-buttonpane').find('button:contains("Salvar")').button({
                        icons: {
                            primary: 'ui-icon-circle-check'
                        }
                    });
                    
                    $('.ui-dialog-buttonpane').find('button:contains("Pesquisar")').button({
                        icons: {
                            primary: 'ui-icon-search'
                        }
                    });

                    $('.ui-dialog-buttonpane').find('button:contains("Cancelar")').button({
                        icons: {
                            primary:  'ui-icon-circle-close'
                        }
                    });
                },
                buttons: {
                    "Salvar" : function(){
                        $("#cadastro_servico").submit();                        
                    },
                    
                    "Pesquisar" : function(){
                        gridService();
                        $("#grid_dialog_service").dialog({
                            title : 'Lista de Serviços',
                            width : 670,
                            height : 370,
                            modal : true,
                            open : function(){
                                $('.ui-dialog-buttonpane').find('button:contains("Excluir")').button({
                                    icons: {
                                        primary: 'ui-icon-trash'
                                    }
                                });
                                
                                $('.ui-dialog-buttonpane').find('button:contains("Editar")').button({
                                    icons: {
                                        primary: 'ui-icon-wrench'
                                    }
                                });
                                
                                $('.ui-dialog-buttonpane').find('button:contains("Cancelar")').button({
                                    icons: {
                                        primary:  'ui-icon-circle-close'
                                    }
                                });
                            },
                            close : function(){                               
                                close();  
                            },
                            buttons : {
                                "Editar" : function(){
                                    var id = $("#grid_service").jqGrid('getGridParam','selrow');                                    
                                    if( id != null ) {
                                        var rowData = $("#grid_service").getRowData(id);               
                                        $("#id_servico").val(rowData["id"]);
                                        $("#nom_servico").val(rowData["name"]);
                                        $("#des_servico").val(rowData["description"]);
                                        $("#num_preco").val(rowData["price"]);
                                        format();
                                        $(this).dialog('close');
                                    }else {
                                        alert("Selecione um registro!");
                                    }
                                },
                                "Excluir" : function(){
                                    var id = $("#grid_service").jqGrid('getGridParam','selrow');                                    
                                    if( id != null ) {
                                        if(confirm("Deseja realmente excluir o registro?")) {                                         
                                            var rowData = $("#grid_service").getRowData(id); 
                                            excluir_servico(rowData["id"]);                                           
                                        }                                        
                                    }else {
                                        alert("Selecione um registro!");
                                    }
                                },
                                "Cancelar" : function(){
                                    clean();
                                    close();
                                }
                            }
                        
                        });
                    },
                    
                    "Cancelar" :  function() {
                        $("#form_cadastro_servico").remove();
                        $("#div_temp").empty();
                        $(this).dialog('destroy');
                    }
                },
                close:function(){
                    $("#form_cadastro_servico").remove();
                    $("#div_temp").empty();
                }
            });
            
            $("#cadastro_servico").validate({
                submitHandler : function(){   
                    cadastro_servico();
                }
            });
            
            format();
            
        });
    });
    
    
    function gridService(){
        $('body').append("<div id='grid_dialog_service'></div>");
        $('#grid_dialog_service').append("<table id='grid_service'></table>");
        $('#grid_dialog_service').append("<table id='pager_service'></table>");
                    
        jQuery("#grid_service").jqGrid({
            width : 630,
            height : 200,
            url:'service/list',
            datatype: "json",
            colNames:['Código Serviço', 'Nome Serviço', "description", "Valor"],
            colModel:[{
                name: 'id', 
                index: 'id', 
                align : "center", 
                width: "20px"
            },{
                name:'name',
                index:'name', 
                align: "left", 
                width: "60px;", 
                sortable : true
            },{
                hidden:true,
                name:'description',
                index:'description', 
                align: "left"
            },{
                name:'price',
                index:'price', 
                align: "left", 
                width: "20px", 
                formatter:'currency',
                sortable: true
            }],
            rowNum:10,
            jsonReader : {
                repeatitems: true,
                cell: '', 
                root : "data"
            },
            onSelectRow: function(id){
            //var rowData = jQuery(this).getRowData(id);               
            //alert(rowData.toSource());
            },
            mtype: "POST",
            pager: '#pager_service',
            sortname: 'name',
            shrinkToFit: true,
            viewrecords: true,
            sortorder: "asc"            
        });
               
        jQuery("#grid_service").navGrid('#pager_service',{
            edit:false,
            add:false,
            del:false, 
            search:false
        })
        .navButtonAdd('#pager_service',{
            caption:"Pesquisar",
            buttonicon:"ui-icon-search",
            onClickButton: function(){
                $('body').append("<div id = 'dialog-search-grid'></grid>");
                $("#dialog-search-grid").dialog({
                    modal : true,
                    title : "Procurar...",
                    width : 400,
                    open : function() {
                        $("#dialog-search-grid").append("<select id='select-search'></select>");
                        $("#select-search").append("<option value='id'>Código Servico</option>");
                        $("#select-search").append("<option value='name'>Nome Serviço</option>");
                        $("#select-search").append("<option value='price'>Valor</option>");
                        $("#dialog-search-grid").append("<input type='text' id='search-text' />");

                        $('.ui-dialog-buttonpane').find('button:contains("Procurar")').button({
                            icons: {
                                primary: 'ui-icon-search'
                            }
                        });

                        $('.ui-dialog-buttonpane').find('button:contains("Cancelar")').button({
                            icons: {
                                primary: 'ui-icon-circle-close'
                            }
                        });
                    },
                    buttons :{
                        "Procurar" : function() {

                            $("#grid_service").setGridParam({
                                'postData':{
                                    field : $("#select-search").val(),
                                    search : $("#search-text").val()
                                }
                            }).trigger("reloadGrid");
                        },
                        "Cancelar" : function() {
                            $("#dialog-search-grid").dialog('close');
                            $("#dialog-search-grid").remove();
                        }
                    },
                    close : function() {
                        $("#dialog-search-grid").remove();                                    
                    }
                })
            },
            position:"first"
        });
    }
});
